package com.taobao.utile;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.response.AlipayTradeQueryResponse;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class PayUtil {

//    @Autowired
//    private OrderService orderService;

    @Value("${alipay.appid}")
    private String APP_ID;
    // 应用私钥
    @Value("${alipay.app-private-key}")
    private String APP_PRIVATE_KEY;
    // 支付宝公钥
    @Value("${alipay.alipay-public-key}")
    private String ALIPAY_PUBLIC_KEY;
    // 沙箱接口路径， 正式路径为 https://openapi.alipay.com/gateway.do
    @Value("${alipay.gateway-url}")
    private String GATEWAY_URL;
    // 支付宝异步通知路径， 付款完毕后异步调用本项目方法，必须为公网ip
    @Value("${alipay.notify-url}")
    private String NOTIFY_URL;
    // 支付宝同步通知路径， 付款完毕后跳转本项目页面，可以不是公网地址
    @Value("${alipay.return-url}")
    private String RETURN_URL;

    private AlipayClient alipayClient = null;

    // 支付宝官方提供的接口
    public String sendRequestToAlipay(String outTradeNo, Float totalAmount, String subject) throws AlipayApiException {

        // 获取初始化的AlipayClient
        alipayClient = new DefaultAlipayClient(GATEWAY_URL, APP_ID, APP_PRIVATE_KEY, "json", "UTF-8", ALIPAY_PUBLIC_KEY, "RSA2");

        // 设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(RETURN_URL);
        alipayRequest.setNotifyUrl(NOTIFY_URL);

        // 商品描述
        String body = "商品描述";
        alipayRequest.setBizContent("{\"out_trade_no\":\"" + outTradeNo + "\","
                + "\"total_amount\":\"" + totalAmount + "\","
                + "\"subject\":\"" + subject + "\","
                + "\"body\":\"" + body + "\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");

        // 请求
        String result = alipayClient.pageExecute(alipayRequest).getBody();
        System.out.println("返回的结果是: " + result);

        return result;
    }

    // 通过订单编号查询
    /**
     * 通过订单编号查询支付状态
     */
    public String query(String id) throws AlipayApiException {
        // 创建查询请求对象
        AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();

        // 构造请求内容
        JSONObject bizContent = new JSONObject();
        bizContent.put("out_trade_no", id); // 使用 out_trade_no 查询
        request.setBizContent(bizContent.toJSONString());

        AlipayTradeQueryResponse response = null;

        try {
            // 执行请求
            response = alipayClient.execute(request);

            // 获取完整响应体
            String body = response.getBody();
            System.out.println("【支付宝查询返回】body: " + body);

            if (response.isSuccess()) {
                System.out.println("✅ 调用成功");
            } else {
                System.out.println("❌ 调用失败，错误码：" + response.getSubCode()
                        + "，描述：" + response.getSubMsg());
            }

            return body;

        } catch (AlipayApiException e) {
            e.printStackTrace();
            System.err.println("🚨 调用支付宝接口出错：");
            System.err.println("错误信息: " + e.getMessage());
            System.err.println("错误详情: " + e.getErrMsg());
            throw e; // 重新抛出异常便于上层处理
        }
    }

}
